import Divider from 'antd/es/divider';
import { AppStore } from '../../../../store';
import { useEffect, useMemo, useState } from 'react';
import { flattenModels } from '../../../../util';
import { ESpaceDirection, ISelectEventParam } from '@manycore/custom-ksg-viewer-sdk';
import Select from 'antd/es/select';
import message from 'antd/es/message';
import AutoComplete from 'antd/es/auto-complete';

const SPACE_DIRECTION = {
    [ESpaceDirection.X]: 'X方向',
    [ESpaceDirection.Y]: 'Y方向',
    [ESpaceDirection.Z]: 'Z方向',
}

export function RulerLineDemo(props: {
    createButton: (infos: Array<{
        /** buttonName */
        name: string,
        onClick: () => void;
    }>) => JSX.Element[]
}) {
    const { createButton } = props;
    const { appState: { app, jsonData, viewInfo } } = AppStore.useContainer();
    const [inputModelIds, setInputModelIds] = useState<string[]>([]);
    const [directions, setDirections] = useState<ESpaceDirection[]>([ESpaceDirection.X, ESpaceDirection.Y, ESpaceDirection.Z]);
    const [dimensionLines, setDimensionLines] = useState<Array<{
        id: string;
        text: string;
    }>>([]);
    const [distanceLines, setDistanceLines] = useState<Array<{
        id: string;
        text: string;
    }>>([]);
    const [prodCatId, setProdCatId] = useState<string>();
    const [brandGoodId, setBrandGoodId] = useState<string>();

    useEffect(() => {
        setDistanceLines([]);
        setDimensionLines([]);
    }, [viewInfo])

    useEffect(() => {
        if (!app) {
            return;
        }
        const onListener = (param: ISelectEventParam) => {
            // 默认将选中的写入到input
            setInputModelIds(param.map(p => p.id));
        }
        app.selectionService.on(onListener);
        return () => app.selectionService.off(onListener);
    }, [app])

    const models = useMemo(() => {
        return flattenModels(jsonData?.paramModel || []);
    }, [jsonData])

    return <>
        <Divider>标尺服务</Divider>
        <Select
            value={inputModelIds}
            mode="multiple"
            style={{ width: '100%' }}
            onChange={(v) => setInputModelIds(v)}
            placeholder="请选择需要展示尺寸线的模型"
            options={(models || []).map((d) => ({
                value: d.id,
                label: d.id,
            }))}
        >
        </Select>
        <Select
            value={directions}
            onChange={(v) => setDirections(v)}
            mode="multiple"
            style={{ width: '100%' }}
            placeholder="请选择一个或多个方向的尺寸线"
            options={Object.entries(SPACE_DIRECTION).map(([key, value]) => ({
                value: key,
                label: value,
            }))}
        >
        </Select>
        {createButton([{
            name: "创建尺寸线",
            onClick: () => {
                if (inputModelIds.length === 0) {
                    message.error('请先选择需要展示尺寸线的模型!');
                    return;
                }
                if (directions.length === 0) {
                    message.error('请请选择一个或多个方向的尺寸线!');
                    return;
                }

                const lineIds = directions.map((d) => {
                    const lineId = app!.rulerLineService.drawDimensionLine({
                        modelIds: inputModelIds,
                        direction: d
                    });

                    return {
                        id: lineId,
                        text: `${SPACE_DIRECTION[d]}:${lineId}`
                    };
                });

                setDimensionLines(lineIds);
            }
        }])}
        <Divider>清除尺寸线</Divider>
        {
            dimensionLines.map((l) => createButton([{
                name: l.text,
                onClick: () => {
                    app!.rulerLineService.removeDimensionLine(l.id);

                    setDimensionLines((prev) => {
                        const newDimensionLines = prev.slice();
                        const index = newDimensionLines.findIndex((v) => v.id === l.id);
                        newDimensionLines.splice(index, 1);
                        return newDimensionLines;
                    })
                }
            }]))
        }
        {createButton([{
            name: '清空尺寸线',
            onClick: () => { app!.rulerLineService.clearDimensionLine(); setDimensionLines([]) }
        }])}
        <Divider>板件距离线</Divider>
        <AutoComplete value={prodCatId} onChange={(data) => setProdCatId(data)} style={{ width: '100%' }} placeholder='输入指定真分类' options={[...new Set(models.map(m => m.prodCatId))].filter(m => !!m).map(v => ({ value: v }))} />
        {createButton([{
            name: '展示指定真分类间距尺寸线',
            onClick: () => {
                if (prodCatId) {
                    const lineId = app!.rulerLineService.drawSpacingDistanceLine({ modelFilter: (data) => data.prodCatId === Number(prodCatId) });
                    setDistanceLines((prev) => {
                        const newLines = [...prev, {
                            id: lineId,
                            text: `${prodCatId}真分类:${lineId}`
                        }];
                        return newLines;
                    })
                }
            }
        }])}
        <AutoComplete value={brandGoodId} onChange={(data) => setBrandGoodId(data)} style={{ width: '100%' }} placeholder='输入指定商品id' options={[...new Set(models.map(m => m.obsBrandGoodId))].filter(m => !!m).map(v => ({ value: v }))} />
        {createButton([{
            name: '展示指定商品间距尺寸线',
            onClick: () => {
                if (brandGoodId) {
                    const lineId = app!.rulerLineService.drawSpacingDistanceLine({ modelFilter: (data) => data.brandGoodId === brandGoodId });
                    setDistanceLines((prev) => {
                        const newLines = [...prev, {
                            id: lineId,
                            text: `${brandGoodId}商品:${lineId}`
                        }];
                        return newLines;
                    })
                }
            }
        }])}
        <Divider>清除间距线</Divider>
        {
            distanceLines.map((l) => createButton([{
                name: l.text,
                onClick: () => {
                    app!.rulerLineService.removeSpacingDistanceLine(l.id);
                    setDistanceLines((prev) => {
                        const newLines = prev.slice();
                        const index = newLines.findIndex((v) => v.id === l.id);
                        newLines.splice(index, 1);
                        return newLines;
                    })
                }
            }]))
        }
        {createButton([{
            name: '清空间距线',
            onClick: () => { app!.rulerLineService.clearSpacingDistanceLine(); setDistanceLines([]) }
        }])}
    </>
}